﻿using Common.Log;
using CommonFunc.FTP;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using WF_Business;
using WF_DataAccess;

namespace CommonFunc.BLL
{
    public class FtpBLL
    {
        public static FtpBLL Instance { get { return new FtpBLL(); } }
        private bool InsertAttchment(string ftpUrl, string userName, string passWord, string iid, string fileName, string lb, string ftpDirctory, string userId)
        {
            string extName = fileName.Substring(fileName.LastIndexOf("."));
            //string.Concat("/", ftpDirctory, "/", iid, "/", lb);
            //var directory = string.IsNullOrWhiteSpace(ftpDirctory) ? Path.Combine(iid, lb, fileName) : Path.Combine(ftpDirctory, iid, lb, fileName);
            var directory = string.IsNullOrWhiteSpace(ftpDirctory) ? string.Concat("/", iid, "/", lb, "/", fileName) : string.Concat("/", ftpDirctory, "/", iid, "/", lb, "/", fileName);
            var ftpPath = string.Concat(userName, ":", passWord, "@", ftpUrl.Replace("ftp://", ""), directory);
            IDataAccess ida = SysParams.OAConnection(true);
            string tbNameSQB = ConfigurationManager.AppSettings["tbNameSQB"];
            try
            {
                string sql = string.Format(@"insert into st_attachment
              (ext_name, name, ftp_path, iid,  ext_type,  input_index ,userid)
                values
              ('{0}', '{1}', '{2}', '{3}', '{4}', '0', '{5}')", extName, fileName, ftpPath, iid, lb, userId);
                ida.RunSql(sql);
                sql = string.Format("update {1} set zt='2' where iid='{0}' and userid='{2}'", iid, tbNameSQB, userId);
                ida.RunSql(sql);
                ida.Close(true);
                return true;
            }
            catch (Exception ex)
            {
                LogManage.addLogErr("InsertAttchment", ex.Message);
                ida.Close(false);
                return false;
            }
        }
        public bool CopyFileToFtp(string ftpUrl, string userName, string passWord, string iid, string fileName, string lb, byte[] fileBytes, string ftpDirctory, string userId, ref string msg)
        {
            bool isTrue = false;
            try
            {
                clsFTP myftp = new clsFTP(new Uri(ftpUrl), userName, passWord);
                myftp.DirectoryPath = "/";
                //var type=string.Empty;
                //switch(lb){
                //    case "身份证":
                //        type="cardid";
                //        break;
                //    case "户口本":
                //        type = "household";
                //        break;
                //    case "结婚证":
                //        type = "marriage ";
                //        break;
                //    case "其它":
                //        type = "other";
                //        break;
                //}
                var filePath = string.IsNullOrWhiteSpace(ftpDirctory) ? string.Concat(iid, "/", lb) : string.Concat(ftpDirctory, "/", iid, "/", lb);
                //var filePath = string.Concat("/", ftpDirctory, "/", iid, "/", lb);
                foreach (var item in filePath.Split('/'))
                {
                    if (!myftp.DirectoryExist(item))
                    {
                        myftp.MakeDirectory(item);
                    }
                    myftp.GotoDirectory(item);
                }
                if (!myftp.UploadFile(fileBytes, fileName))
                {
                    var str = "上传文件" + fileName + "过程出错。";
                    msg = str;
                    throw new Exception(str);
                }
                isTrue = InsertAttchment(ftpUrl, userName, passWord, iid, fileName, lb, ftpDirctory, userId);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                LogManage.addLogErr("CopyFileToFtp", ex.Message);
            }
            return isTrue;
        }

        /// <summary>
        /// 列出FTP服务器上面当前目录的所有文件
        /// </summary>
        public FileStruct[] ListFiles(string ftpUrl, string userName, string passWord, string iid, string ftpDirctory)
        {
            try
            {
                clsFTP myftp = new clsFTP(new Uri(ftpUrl), userName, passWord);
                //myftp.DirectoryPath = string.Concat("/", ftpDirctory, "/", iid, "/");
                myftp.DirectoryPath = string.IsNullOrWhiteSpace(ftpDirctory) ? string.Concat("/", iid, "/") : string.Concat("/", ftpDirctory, "/", iid, "/");
                var list = myftp.ListFiles();
                return list;
            }
            catch (Exception ex)
            {
                LogManage.addLogErr("ListFiles", ex.Message);
                return null;
            }
        }

        public bool DownloadFile(string ftpUrl, string userName, string passWord, string iid, string RemoteFileName, string LocalPath, string LocalFileName)
        {
            try
            {
                clsFTP myftp = new clsFTP(new Uri(ftpUrl), userName, passWord);
                myftp.GotoDirectory(iid);
                return myftp.DownloadFile(RemoteFileName, LocalPath, LocalFileName);
            }
            catch (Exception ex)
            {
                LogManage.addLogErr("DownloadFile", ex.Message);
                return false;
            }
        }

        public bool DeleteFtpFile(string ftpUrl, string userName, string passWord, string remoteDirectoryName, string remoteFileName)
        {
            try
            {
                clsFTP myftp = new clsFTP(new Uri(ftpUrl), userName, passWord);
                myftp.DirectoryPath = remoteDirectoryName;
                if (myftp.FileExist(remoteFileName))
                {
                    myftp.DeleteFile(remoteFileName);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                LogManage.addLogErr("DeleteFtpFile", ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 下载FTP文件
        /// </summary>
        /// <param name="ftpUrl"></param>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <param name="iid"></param>
        /// <param name="LocalPath"></param>
        /// <param name="ftpDirctory">目录格式data或data/demo</param>
        /// <returns></returns>
        public bool DownloadFileForDirectory(string ftpUrl, string userName, string passWord, string iid, string LocalPath, string ftpDirctory)
        {
            try
            {
                clsFTP myftp = new clsFTP(new Uri(ftpUrl), userName, passWord);
                //var directoryName = string.Concat("/", ftpDirctory, "/", iid, "/");
                var directoryName = string.IsNullOrWhiteSpace(ftpDirctory) ? string.Concat("/", iid, "/") : string.Concat("/", ftpDirctory, "/", iid, "/");
                myftp.DirectoryPath = directoryName;
                var arrLb = myftp.ListDirectories();
                var dir = directoryName.TrimStart('/').TrimEnd('/');
                arrLb.ToList().ForEach(t =>
                {
                    myftp.DirectoryPath = string.Concat(directoryName, t.Name, "/");
                    var list = myftp.ListFiles();
                    list.ToList().ForEach(l =>
                    {
                        DownloadFile(ftpUrl, userName, passWord, dir, Path.Combine(t.Name, l.Name), Path.Combine(LocalPath, t.Name), l.Name);
                    });
                });
                return true;
            }
            catch (Exception ex)
            {
                LogManage.addLogErr("DownloadFileForDirectory", ex.Message);
                return false;
            }
        }
    }
}
